import request from '@/axios'

export interface DifyResponse {
  answer: string
  id: string
  created_at: string
  message_id: string
  conversation_id: string
  metadata: any
}

export interface DifyStreamingResponse {
  id: string
  message_id: string
  conversation_id: string
  created_at: string
  text: string
  tool_calls: any[]
  metadata: any
}

export interface DifyRequest {
  query: string
  conversation_id?: string
  user?: string
  response_mode?: 'streaming' | 'blocking'
  inputs?: Record<string, any>
}

// Dify API接口参数
export interface DifyConfig {
  apiKey: string
  apiBase: string
}

// 发送消息到Dify API
export const sendMessageToDify = (
  data: DifyRequest,
  config: DifyConfig,
  onMessage?: (text: string, event: string) => void,
  onFinish?: (response: DifyStreamingResponse) => void,
  onError?: (error: any) => void
) => {
  // 流式响应处理
  if (data.response_mode === 'streaming') {
    return streamRequest(data, config, onMessage, onFinish, onError)
  }

  // 非流式响应
  return request.post<IResponse<DifyResponse>>({
    url: `${config.apiBase}/chat-messages`,
    data,
    headers: {
      Authorization: `Bearer ${config.apiKey}`,
      'Content-Type': 'application/json'
    }
  })
}

// 流式请求处理
const streamRequest = (
  data: DifyRequest,
  config: DifyConfig,
  onMessage?: (text: string, taskID: string, event: string) => void,
  onFinish?: (response: DifyStreamingResponse) => void,
  onError?: (error: any) => void
) => {
  return new Promise((resolve, reject) => {
    let fullText = ''
    let responseObj: DifyStreamingResponse | null = null

    console.log('开始发送流式请求到:', `${config.apiBase}/chat-messages`)
    console.log('请求数据:', data)

    fetch(`${config.apiBase}/chat-messages`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${config.apiKey}`,
        Accept: 'text/event-stream'
      },
      body: JSON.stringify(data)
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP 错误! 状态: ${response.status} ${response.statusText}`)
        }

        if (!response.body) {
          throw new Error('响应没有返回数据流!')
        }

        console.log('收到响应，开始解析流')

        // 创建一个流式解析器
        const reader = response.body.getReader()
        const decoder = new TextDecoder()
        let buffer = ''

        // 返回一个promise，在处理完所有块后resolve
        return new ReadableStream({
          start(controller) {
            function push() {
              reader
                .read()
                .then(({ done, value }) => {
                  if (done) {
                    controller.close()
                    return
                  }

                  // 解码新收到的块并添加到缓冲区
                  buffer += decoder.decode(value, { stream: true })

                  // 处理收到的数据
                  const lines = buffer.split('\n\n')
                  buffer = lines.pop() || '' // 保留最后一个不完整的块

                  for (const line of lines) {
                    if (line.trim() && line.startsWith('data: ')) {
                      const jsonData = line.substring(6).trim()

                      if (jsonData === '[DONE]') {
                        console.log('收到[DONE]标记')
                        if (responseObj && onFinish) {
                          onFinish(responseObj)
                        }
                        continue
                      }

                      try {
                        const data = JSON.parse(jsonData)
                        console.log('解析的数据:', data)

                        if (data.event === 'message') {
                          if (data.answer && data.answer !== fullText) {
                            fullText = data.answer
                            if (onMessage) onMessage(fullText, data.task_id, data.event)
                          }
                        } else if (data.event === 'message_end') {
                          responseObj = data
                          if (onFinish) onFinish(data)
                        } else if (data.event === 'error') {
                          console.error('接收到错误事件:', data.error)
                          if (onError) onError(data.error)
                          reject(data.error)
                        } else if (data.event === 'done') {
                          responseObj = data
                          if (onFinish) onFinish(data)
                        } else if (data.answer || data.text) {
                          // 处理非事件格式的响应
                          const messageText = data.answer || data.text
                          if (messageText && messageText !== fullText) {
                            fullText = messageText
                            if (onMessage) onMessage(fullText, data.task_id, data.event)
                          }

                          // 保存完整响应
                          responseObj = data
                        }
                      } catch (error) {
                        console.error('解析SSE数据出错:', error, '原始数据:', jsonData)
                      }
                    }
                  }

                  controller.enqueue(value)
                  push()
                })
                .catch((error) => {
                  console.error('读取流出错:', error)
                  controller.error(error)
                  if (onError) onError(error)
                  reject(error)
                })
            }

            push()
          }
        })
      })
      .then(() => {
        console.log('流处理完成')
        resolve(responseObj)
      })
      .catch((error) => {
        console.error('请求出错:', error)
        if (onError) onError(error)
        reject(error)
      })
  })
}

// ============================停止响应===========================
// Dify API接口参数
export interface stopDifyConfig {
  apiKey: string
  apiBase: string
  taskID: string
}
export interface stopDifyRequest {
  user?: string
}

// 停止响应 仅支持流式模式
export const stopMessageToDify = (
  data: stopDifyRequest,
  config: stopDifyConfig,
  onFinish?: (response: any) => void,
  onError?: (error: any) => void
) => {
  // 流式响应处理
  return new Promise((resolve, reject) => {
    console.log('开始发送流式请求到:', `${config.apiBase}/chat-messages/${config.taskID}/stop`)
    console.log('请求数据:', data)

    fetch(`${config.apiBase}/chat-messages/${config.taskID}/stop`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${config.apiKey}`,
        Accept: 'text/event-stream'
      },
      body: JSON.stringify(data)
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP 错误! 状态: ${response.status} ${response.statusText}`)
        }

        if (!response.body) {
          throw new Error('响应没有返回数据流!')
        }

        console.log('收到响应', response)
        if (onFinish) onFinish(response)
        resolve(response)
      })
      .catch((error) => {
        console.error('请求出错:', error)
        if (onError) onError(error)
        reject(error)
      })
  })
}
